<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017 http://www.sycit.cn
// +----------------------------------------------------------------------
// | Author: Peter.Zhang  <hyzwd@outlook.com>
// +----------------------------------------------------------------------
// | Date:   2017/9/15
// +----------------------------------------------------------------------
// | Title:  Handle.php
// +----------------------------------------------------------------------
namespace app\index\controller;

use app\index\model\Purchase;
use app\index\model\Finance;
use app\index\model\PurchaseAffirm;
use think\Request;
use think\Session;
use think\Db;
use think\Url;

class Handle extends Common_base
{
    protected $handle;  //操作方式
    protected $name;    //操作对象
    protected $pnumber; //操作订单号
    protected $sycitcn; //操作验证

    public function _initialize()
    {
        // 是否有权限
        IS_ROOT([1,4])  ? true : $this->error('没有权限');
        $Request = Request::instance();
        $this->handle  = $Request->param('handle');
        $this->name    = $Request->param('name');
        $this->pnumber = $Request->param('pid');
        $this->sycitcn = $Request->param('sycitcn');

        return parent::_initialize(); // TODO: Change the autogenerated stub
    }

    //销售人员确认订单
    public function affirm() {
        // 是否有权限
        IS_ROOT([1,2])  ? true : $this->error('没有权限');

        //验证数据
        $result = $this->validate(['__token__' => $this->sycitcn],['__token__'=>'token']);
        if(true !== $result){
            //$this->error('数据提交错误，请返回刷新', Url::build('orders/index'));
        }

        if ($this->handle !='affirm' || !Purchase::get(['pnumber' => $this->pnumber])) {
            $this->error('数据提交错误，请返回刷新2');
            //p($this->handle);
        }
        $Purchase = new Purchase();
        $Request = Request::instance();
        if ($Request->isPost()) {
            //提交动作
            $data=array();
            $file = request()->file('pc_img'); // 获取上传文件
            if (!empty($file)) {
                // 上传图片 移动 用 rule('uniqid') 无序
                $info = $file->validate([
                    'type' => 'image/jpeg,image/gif,image/png', // 上传文件头
                    'ext' => 'jpeg,jpg,png', // 上传类型
                    'size'=> 3 * 1024 * 1024, // 上传大小
                ])->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'images');
                // 判断信息
                if ($info) {
                    $pc_img = DS . 'uploads'. DS .'images'. DS . $info->getSaveName();
                    //替换windows 下的 \
                    $data['a_img'] = str_replace("\\",'/',$pc_img);
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            }
            $data['a_pnumber'] = $this->pnumber;
            $data['a_affirm'] = $Request->param('affirm_ok');
            $data['a_remark'] = $Request->param('remark');
            $model = new PurchaseAffirm();
            $model->data($data);
            $result = $model->allowField(true)->save();
            if ($result) {
                $Purchase->allowField('affirm')->save(['affirm'=>1],['pnumber'=>$this->pnumber]);
                $this->success('此订单操作成功',Url::build('product/color'));
            } else {
                $this->error('服务器错误，请通知管理员');
            }
        } else {
            $data = $Purchase->where('pnumber', $this->pnumber)->where('affirm','=',0)->field('pnumber,pbname,pcsname,pcus_id,pamount')->find();
            if (empty($data)) {
                $this->error('数据提交错误，请返回刷新', Url::build('orders/index'));
            }
            $assign = [
                'title' => '确认订单',
                'data'  => $data,
            ];
            $this->assign($assign);
            return $this->fetch();
        }
    }

    //财务确认订金收款
    public function deposit() {
        // 是否有权限
        IS_ROOT([1,4])  ? true : $this->error('没有权限');

        //验证数据
        $result = $this->validate(['__token__' => $this->sycitcn],['__token__'=>'token']);
        if(true !== $result){
            $this->error('数据提交错误，请返回刷新', Url::build('finance/index'));
        }

        if ($this->handle !='deposit' || !Purchase::get(['pnumber' => $this->pnumber])) {
            $this->error('数据提交错误，请返回刷新2');
        }

        $Purchase = new Purchase();
        $Request = Request::instance();

        if ($Request->isPost()) {
            //提交动作
            $file = request()->file('pc_img'); // 获取上传文件

            if (!empty($file)) {
                // 上传图片 移动 用 rule('uniqid') 无序
                $info = $file->validate([
                    'type' => 'image/jpeg,image/gif,image/png', // 上传文件头
                    'ext' => 'jpeg,jpg,png', // 上传类型
                    'size'=> 3 * 1024 * 1024, // 上传大小
                ])->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'images');
                // 判断信息
                if ($info) {
                    $pc_img = DS . 'uploads'. DS .'images'. DS . $info->getSaveName();
                    //替换windows 下的 \
                    $fs_img = str_replace("\\",'/',$pc_img);
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            } else {
                $fs_img='';
            }
            $data = $Purchase->where('pnumber', $this->pnumber)->field('pcus_id,pbname,pcsname,pamount')->find();
            $djin_amount = sprintf("%.2f", $Request->param('djin_amount')); //订金金额 四舍五入
            $shoukuan_time = strtotime($Request->param('shoukuan_time')); //收款日期
            //判断订金是否比订单金额大 和 小于数值
            if ($djin_amount > $data['pamount'] || $djin_amount < '0') {
                $this->error('订金金额不能大过订单金额和小于0');
            }
            $finance = new Finance();
            $data = [
                'fpnumber' => $this->pnumber,
                'fcus_id' => $data['pcus_id']['cus_id'],
                'fcus_name' => $data['pcus_id']['cus_duty'],
                'sort' => '1',
                'amount' => $djin_amount,
                'fuid' => Session::get("user_id"),
                'shoukuan_time' => $shoukuan_time,
            ];
            $finance->data($data);
            $result = $finance->allowField(true)->save();
            if ($result) {
                //插入附表数据
                Db::name('finance_schedule')->insert([
                    'fs_fid' => $finance->fid,
                    'fs_img' => $fs_img,
                    'fs_remark' => $Request->param('remark')
                ]);
                //更新订单表状况
                $Purchase->allowField(['pshoudj','status'])->save(['pshoudj'=>'1','status'=>'1'],['pnumber'=>$this->pnumber]);

                $this->success('操作成功',Url::build('product/color'));
            } else {
                $this->error('保存数据错误，请联系管理员');
            }

        } else {
            //修改动作
            $data = $Purchase->where('pnumber', $this->pnumber)->where('affirm','=',1)->where('status', '=', 0)->find();
            if (empty($data)) {
                $this->error('参数错误', Url::build('finance/index'));
            }
            $sum_amount = Db::name('purchase_orders')->where('ord_pnumber',$data['pnumber'])->sum('amount'); //统计附表总金额
            $youhuije = ($sum_amount * 1) - ($data['pamount'] * 1); //计算优惠后的金额

            $assign = [
                'title' => '销售收款',
                'data'  => $data,
                'sum_amount'  => $sum_amount,
                'youhuije'  => $youhuije,
            ];
            $this->assign($assign);
            return $this->fetch();
        }
    }

    //确认余款
    public function balance() {
        // 是否有权限
        IS_ROOT([1,4])  ? true : $this->error('没有权限');
//验证数据
        $result = $this->validate(['__token__' => $this->sycitcn],['__token__'=>'token']);
        if(true !== $result){
            //$this->error('数据提交错误，请返回刷新', Url::build('finance/index'));
        }

        if ($this->handle !='deposit' || !Purchase::get(['pnumber' => $this->pnumber])) {
            $this->error('数据提交错误，请返回刷新2');
        }

        $Purchase = new Purchase();
        $Request = Request::instance();

        if ($Request->isPost()) {
            //提交动作
            $file = request()->file('pc_img'); // 获取上传文件

            if (!empty($file)) {
                // 上传图片 移动 用 rule('uniqid') 无序
                $info = $file->validate([
                    'type' => 'image/jpeg,image/gif,image/png', // 上传文件头
                    'ext' => 'jpeg,jpg,png', // 上传类型
                    'size'=> 3 * 1024 * 1024, // 上传大小
                ])->move(ROOT_PATH . 'public' . DS . 'uploads'. DS .'images');
                // 判断信息
                if ($info) {
                    $pc_img = DS . 'uploads'. DS .'images'. DS . $info->getSaveName();
                    //替换windows 下的 \
                    $fs_img = str_replace("\\",'/',$pc_img);
                } else {
                    // 上传失败获取错误信息
                    $this->error($file->getError());
                }
            } else {
                $fs_img='';
            }
            $data = $Purchase->where('pnumber', $this->pnumber)->field('pcus_id,pbname,pamount,pshengcwc')->find();
            $djin_amount = sprintf("%.2f", $Request->param('djin_amount')); //订金金额 四舍五入
            $shoukuan_time = strtotime($Request->param('shoukuan_time')); //收款日期
            //判断订金是否比订单金额大 和 小于数值
            if ($djin_amount > $data['pamount'] || $djin_amount < '0') {
                $this->error('金额不能大过订单金额和小于0');
            }
            $finance = new Finance();
            $save = [
                'fpnumber' => $this->pnumber,
                'fcus_id' => $data['pcus_id']['cus_id'],
                'fcus_name' => $data['pcus_id']['cus_duty'],
                'sort' => '2',
                'amount' => $djin_amount,
                'fuid' => Session::get("user_id"),
                'shoukuan_time' => $shoukuan_time,
            ];
            $finance->data($save);
            $result = $finance->allowField(true)->save();
            if ($result) {
                //插入附表数据
                Db::name('finance_schedule')->insert([
                    'fs_fid' => $finance->fid,
                    'fs_img' => $fs_img,
                    'fs_remark' => $Request->param('remark')
                ]);

                //更新订单表状况
                if ($data['pshengcwc'] == 1) {
                    //如果生产完成
                    $Purchase->allowField(['pshoudj','status'])->save(['pshoudj'=>'2', 'status'=>'4'],['pnumber'=>$this->pnumber]);
                } else {
                    $Purchase->allowField(['pshoudj'])->save(['pshoudj'=>'2'],['pnumber'=>$this->pnumber]);
                }

                $this->success('操作成功',Url::build('product/color'));
            } else {
                $this->error('保存数据错误，请联系管理员');
            }

        } else {
            //修改动作
            $data = $Purchase->where('pnumber', $this->pnumber)->where('pshoudj','=',1)->where('status', '<', 5)->find();
            if (empty($data)) {
                $this->error('参数错误', Url::build('finance/index'));
            }
            $sum_amount = Db::name('purchase_orders')->where('ord_pnumber',$data['pnumber'])->sum('amount'); //统计附表总金额
            $youhuije = ($sum_amount * 1) - ($data['pamount'] * 1); //计算优惠后的金额
            //已收款详细
            $finance_model = new Finance();
            $finance = $finance_model->where('fpnumber', $this->pnumber)->select();
            $fcount = $finance_model->where('fpnumber', $this->pnumber)->count();
            $fsum = $finance_model->where('fpnumber', $this->pnumber)->sum('amount');
            $yukuan = sprintf("%.2f", $data['pamount']) - sprintf("%.2f", $fsum);
            $assign = [
                'title' => '销售收款',
                'data'  => $data,
                'sum_amount'  => $sum_amount,
                'youhuije'  => $youhuije,
                'finance'  => $finance,
                'fcount'  => $fcount,
                'fsum'  => $fsum,
                'yukuan'  => $yukuan,
            ];
            $this->assign($assign);
            return $this->fetch();
        }
    }
}